package org.tio.webpack.app.http;

import java.io.File;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.http.common.HttpConfig;
import org.tio.http.common.session.id.impl.SnowflakeSessionIdGenerator;
import org.tio.http.server.HttpServerStarter;
import org.tio.http.server.handler.DefaultHttpRequestHandler;
import org.tio.http.server.mvc.Routes;
import org.tio.http.server.session.DomainSessionCookieDecorator;
import org.tio.http.server.view.ModelGenerator;
import org.tio.http.server.view.freemarker.FreemarkerConfig;
import org.tio.server.ServerGroupContext;
import org.tio.utils.SystemTimer;
import org.tio.webpack.init.PropInit;
import org.tio.webpack.model.Root;
import org.tio.webpack.utils.Threads;

import com.jfinal.kit.PropKit;
import com.xiaoleilu.hutool.util.ArrayUtil;

import freemarker.template.Configuration;
import freemarker.template.TemplateExceptionHandler;

/**
 * @author tanyaowu
 * 2017年7月19日 下午4:59:04
 */
public class HttpServerInit {
	private static Logger log = LoggerFactory.getLogger(HttpServerInit.class);

	//	public static HttpConfig httpConfig;
	//
	//	public static IHttpRequestHandler requestHandler;

	public static HttpServerStarter httpServerStarter;
	
	public static HttpConfig httpConfig;
	
	public static Routes routes = null;
	
	public static DefaultHttpRequestHandler defaultHttpRequestHandler;

	public static void init(Root model,  ModelGenerator modelGenerator) throws Exception {
		long start = SystemTimer.currentTimeMillis();

		PropInit.init();

		
		//【【------------ 设置 httpconfig start ------------------
		//监听端口
		int port = PropKit.getInt("http.port");
		//session超时时间
		long sessionTimeout = PropKit.getLong("http.session.timeout", HttpConfig.DEFAULT_SESSION_TIMEOUT);//HttpConfig.DEFAULT_SESSION_TIMEOUT;
		String contextpath = PropKit.get("http.contextpath", "");
		String suffix = PropKit.get("http.suffix", "");
		httpConfig = new HttpConfig(port, sessionTimeout, contextpath, suffix);
		
		Integer maxLiveTimeOfStaticRes = PropKit.getInt("http.maxLiveTimeOfStaticRes");
		if (maxLiveTimeOfStaticRes != null) {
			httpConfig.setMaxLiveTimeOfStaticRes(maxLiveTimeOfStaticRes);
		}
		
		
		
		//分布式环境中，用于高效生成uuid的
		int workerid = PropKit.getInt("uuid.workerid");
		int datacenter = PropKit.getInt("uuid.datacenter");
		SnowflakeSessionIdGenerator sessionIdGenerator = new SnowflakeSessionIdGenerator(workerid, datacenter);//更高效的Snowflake sessionId生成器，取代默认的sessionId生成器
		httpConfig.setSessionIdGenerator(sessionIdGenerator);

		httpConfig.setSessionCookieName(PropKit.get("http.session.cookie.name", HttpConfig.SESSION_COOKIE_NAME));
		
		//html/css/js等的根目录，支持classpath:，也支持绝对路径
		String pageRoot = PropKit.get("http.page", null);
		httpConfig.setPageRoot(pageRoot);
		
		//用于存储HttpSession对象
//		GuavaRedisCache guavaRedisCache = GuavaRedisCache.register(RedisUtils.get(), HttpConfig.SESSION_CACHE_NAME, null, sessionTimeout);
//		httpConfig.setSessionStore(guavaRedisCache);
		httpConfig.setProxied(PropKit.getBoolean("http.isproxied", false));
		
		//------------ 设置 httpconfig end ------------------】】
		
		
		//【【------------ 设置 Routes start ------------------
		
//		String[] scanPackages = new String[] { TioLiveWebServerRoot.class.getPackage().getName() };//tio-mvc需要扫描的根目录包
//		routes = new Routes(scanPackages);
		//------------ 设置 Routes end ------------------】】
		
		
		
		//【【------------ 设置 DefaultHttpRequestHandler start ------------------
		DefaultHttpRequestHandler requestHandler = new DefaultHttpRequestHandler(httpConfig, routes);
		
		
		
		File pageRootFile = httpConfig.getPageRoot();
		if (pageRootFile != null) {
			if (!pageRootFile.exists()) {
				log.error("文件{}不存在，请检查app-env.properties文件的http.page配置项", pageRootFile.getCanonicalPath());
				System.exit(1);
				return;
			}
		}
		
		log.info("源目录:{}", pageRootFile.getCanonicalPath());

		Configuration cfg = new Configuration(Configuration.getVersion());
		cfg.setDirectoryForTemplateLoading(httpConfig.getPageRoot());
		cfg.setDefaultEncoding("UTF-8");
		cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
		cfg.setLogTemplateExceptions(true);
		cfg.setWrapUncheckedExceptions(true);
		
		String[] suffixes = StringUtils.split(PropKit.get("freemarker.suffix", ""), "|");
				
		FreemarkerConfig freemarkerConfig = new FreemarkerConfig(cfg, modelGenerator, suffixes);
		requestHandler.setFreemarkerConfig(freemarkerConfig);

		String cookieDomain = PropKit.get("http.cookie.domain");  // 形如: ".baidu.com"
		DomainSessionCookieDecorator domainSessionCookieDecorator = new DomainSessionCookieDecorator(cookieDomain);
		requestHandler.setSessionCookieDecorator(domainSessionCookieDecorator);
		
		TioWebpackHttpServerInterceptor tioWebpackHttpServerInterceptor = new TioWebpackHttpServerInterceptor();
		tioWebpackHttpServerInterceptor.setModel(model);
		requestHandler.setHttpServerInterceptor(tioWebpackHttpServerInterceptor);
		
		
		//------------ 设置 DefaultHttpRequestHandler end ------------------】】
		
		
		//创建HttpServerStarter
		httpServerStarter = new HttpServerStarter(httpConfig, requestHandler, Threads.tioExecutor, Threads.groupExecutor);

		ServerGroupContext serverGroupContext = httpServerStarter.getServerGroupContext();
//		serverGroupContext.ipStats.addDurations(Const.IpStatDuration.IPSTAT_DURATIONS, TioLiveIpStatListener.web);
		
//		IpPathAccessStats ipPathAccessStats = new IpPathAccessStats(serverGroupContext, TioLiveIpPathAccessStatListener.ME, Const.IpPathAccessStatDuration.IP_PATH_ACCESS_STAT_DURATIONS);
//		requestHandler.setIpPathAccessStats(ipPathAccessStats);

		//启动httpserver
		httpServerStarter.start();

		long end = SystemTimer.currentTimeMillis();
		long iv = end - start;
		log.info("TioHttpServer启动完毕,耗时:{}ms,访问地址:http://127.0.0.1:{}", iv, port);
	}

	/**
	 *
	 * @author tanyaowu
	 */
	public HttpServerInit() {
	}
	
	public static void main(String[] args) {
		String[] sss = StringUtils.split("txt|js|css|html|htm|json|xml", "|");
		System.out.println(sss);
		
		boolean xx = ArrayUtil.contains(sss, "txt");
		
		System.out.println(xx);
	}
}
